# 财务系统
from web.models import FinancialFlow,User
from django.http import JsonResponse
from django import forms
from django.forms.models import model_to_dict
from django.core.paginator import Paginator
class FinancialFlowForm(forms.ModelForm):
    class Meta:
        model = FinancialFlow
        fields = ["flow_type", "description", "amount", "user_id"]

# 创建财务流水
def create_financial_flow(request):
    """
    必要的参数:
    flow_type: 流水类型 0:收入 1:支出
    description: 流水描述
    amount: 金额
    user_id: 操作用户id
    """
    if request.method == "POST":
        form = FinancialFlowForm(request.POST)
        if form.is_valid():
            form.save()
            # 返回财务信息
            financial_info = model_to_dict(form.instance)
            return JsonResponse({"code": 200, "message": "创建财务流水成功", "data": financial_info})
        else:
            return JsonResponse({"code": 400, "message": "创建财务流水失败"})


# 获取财务流水
def get_financial_flow(request):
    page = request.GET.get("page", 1)
    page_size = request.GET.get("page_size", 10)
    # 获取财务流水
    financial_flow = FinancialFlow.objects.all().order_by("-created_at")
    # 分页
    paginator = Paginator(financial_flow, page_size)
    page_obj = paginator.page(page)
    # 处理数据
    data = []
    for item in page_obj.object_list:
        new_data = model_to_dict(item)
        # 时间
        new_data["created_at"] = item.created_at.strftime("%Y-%m-%d %H:%M:%S")
        new_data["updated_at"] = item.updated_at.strftime("%Y-%m-%d %H:%M:%S")
        new_data['user_name'] = item.user_id.username
        data.append(new_data)
    
    result = {
        "page": page,
        "page_size": page_size,
        "total": paginator.count,
        "data": data
    }
    # 返回财务流水
    return JsonResponse({"code": 200, "message": "获取财务流水成功", "data": result})



